import time
import uuid
from datetime import datetime
from fastapi import Request
from api_middleware import BaseMiddleware, set_body, api_wrap
from common import logger


class GlobalRequestMiddleware(BaseMiddleware):

    async def dispatch(self, request: Request, call_next):
        # 给当前的app这是当前的请求上下文对象
        request_id = uuid.uuid4()
        request.state.__setattr__("request_id", str(request_id))
        request.state.__setattr__("start_time", time.time())
        response = await call_next(request)

        resp_body = [section async for section in response.__dict__['body_iterator']]
        response.__setattr__('body_iterator', api_wrap(resp_body))
        return response
